import React, { ReactNode } from "react";

// 数据下载导出
export const downloadStringAsFile = (data: any, filename: string, mimeType = 'text/plain') => {
  const blob = new Blob([data], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  // 将 a 元素附加到 DOM 中
  document.body.appendChild(a);
  // 模拟点击链接以触发下载
  a.click();
  // 从 DOM 中移除 a 元素
  document.body.removeChild(a);
  // 释放对象 URL
  URL.revokeObjectURL(url);
}

export const downloadImage = (url: string, filename: string = 'none.jpg') => {
  if (!url) {
    return
  }
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

export const errorImage=""

export const uniqArray = (arr: any, fn: Function) => {
  const set = new Set<string>()
  const res: any[] = []
  arr.forEach((item: any) => {
    const key = fn(item)
    if (!set.has(key)) {
      set.add(key)
      res.push(item)
    }
  });
  return res
}

export function isReactNode(obj: any): obj is ReactNode {
  return obj !== null && typeof obj !== 'undefined';
}

export function isReactFunctionalComponent(obj: any): obj is React.FC {
  return typeof obj === 'function' && obj.hasOwnProperty('prototype') && obj.prototype.isReactComponent;
}

export function isString(obj: any): obj is string {
  return typeof obj === 'string'
}

export function spliceString(str: string, len: number = 30, suffix: string = '...'): string {
  if (!str) {
    return ''
  }
  return str.slice(0, len) + suffix
}